<template>
  <el-row style="height:100%">
    <!-- 左侧：患者列表 -->
    <el-col
        v-if="showPatientList"
        :span="5"
        class="patient-list-col"
    >
      <PatientList
          :patients="patients"
          :total="total"
          @refresh="loadPatients"
          @select="onSelectPatient"
      />
    </el-col>

    <!-- 右侧：医生工作区 -->
    <el-col
        :span="showPatientList ? 19 : 24"
        class="workstation-col"
    >
      <!-- 头部：隐藏按钮 + 患者信息 + 刷新 -->
      <el-card
          class="workstation-header-card"
          shadow="never"
          :body-style="{ padding: 0 }"
      >
        <template #header>
          <div class="header-content">
            <el-button type="text" @click="togglePatientList">
              {{ showPatientList ? '隐藏患者栏' : '显示患者栏' }}
            </el-button>

            <span class="header-text">
              <template v-if="currentPatient">
                患者姓名：{{ currentPatient.realname }}，
                病历号：{{ currentPatient.casenumber }}，
                性别：{{ currentPatient.gender === 71 ? '男' : '女' }}，
                年龄：{{ currentPatient.age }}
              </template>
              <template v-else>
                请选择患者
              </template>
            </span>

            <el-button type="text" @click="reloadCurrentPatient">
              刷新
            </el-button>
          </div>
        </template>
      </el-card>

      <!-- Tab 切换 -->
      <el-tabs v-model="activeTab" class="workstation-tabs">
        <el-tab-pane label="病历首页" name="record">
          <MedicalRecordHome :patient="currentPatient" />
        </el-tab-pane>
        <el-tab-pane label="检验申请" name="lab">
          <!-- 传入 regist-id 而不是整个 patient 对象 -->
          <LabApplication
              v-if="currentPatient && currentPatient.id"
              :regist-id="currentPatient.id"
          />
        </el-tab-pane>
        <el-tab-pane label="门诊确诊" name="diagnosis">
          <DiagnosisConfirm :patient="currentPatient" />
        </el-tab-pane>
      </el-tabs>
    </el-col>
  </el-row>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import axios from 'axios'
import { useCounterStore } from '@/stores/counter'

/* 子组件 */
import PatientList        from './components/PatientList.vue'
import MedicalRecordHome  from './pages/MedicalRecordHome.vue'
import LabApplication     from './pages/LabApplication.vue'
import DiagnosisConfirm   from './pages/DiagnosisConfirm.vue'

/* 登录医生 ID（始终保持最新） */
const counterStore = useCounterStore()
const doctorId = computed(() => counterStore.userId)

/* 组件状态 */
const patients        = ref([])
const total           = ref(0)
const currentPatient  = ref(null)
const activeTab       = ref('record')
const showPatientList = ref(true)

/* 拉取患者列表 */
async function loadPatients () {
  if (!doctorId.value) return
  const { data } = await axios.get('/api/doctor/patients', {
    params : { kw:'', type:'unseen', page:1, pageSize:20 },
    headers: { 'X-User-Id': doctorId.value }
  })
  patients.value = data.records || data.data || []
  total.value    = data.total  ?? patients.value.length
}

/* 选中 / 刷新单个患者 */
function onSelectPatient (p) {
  currentPatient.value = p
}
async function reloadCurrentPatient () {
  if (!currentPatient.value || !doctorId.value) return
  const { data } = await axios.get('/api/doctor/patients', {
    params : {
      kw: currentPatient.value.realname,
      type:'unseen',
      page:1,
      pageSize:1
    },
    headers: { 'X-User-Id': doctorId.value }
  })
  const rec = (data.records || data.data || [])[0]
  if (rec) currentPatient.value = rec
}

/* 隐藏/显示患者栏 */
function togglePatientList () {
  showPatientList.value = !showPatientList.value
}

/* 登录医生变化时重拉患者列表 */
watch(
    doctorId,
    () => {
      patients.value       = []
      currentPatient.value = null
      loadPatients()
    },
    { immediate: true }
)

onMounted(loadPatients)
</script>

<style scoped>
.patient-list-col   { border-right:1px solid #ebeef5; overflow:auto; }
.workstation-col    { display:flex; flex-direction:column; background:#f0f9ff; padding:0 20px; }
.workstation-header-card { margin-bottom:4px; background:transparent; }
.header-content     { display:grid; grid-template-columns:auto 1fr auto; align-items:center; padding:8px 20px; background:#fff; border-bottom:1px solid #ebeef5; }
.header-text        { font-size:14px; color:#303133; text-align:center; }
.workstation-tabs   { margin-top:4px !important; }
</style>
